 import socket

  # 创建 socket 对象
  server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  # 绑定地址和端口
  server_address = ('192.168.43.159', 8888)
  server_socket.bind(server_address)

  # 监听连接
  server_socket.listen(1)
  print('服务器正在监听 {}:{}'.format(*server_address))

  # 接受客户端连接
  client_socket, client_address = server_socket.accept()
  print('接受来自 {} 的连接'.format(client_address))

  # 打开文件以记录消息
  with open('server_messages.txt', 'a', encoding='utf-8') as server_file:
      while True:
          # 接收客户端消息
          data = client_socket.recv(1024).decode('utf-8')
          if not data:
              break
          print('客户端说: {}'.format(data))
          server_file.write(f'客户端发送: {data}\n')

          # 发送消息给客户端
          message = input('请输入要发送给客户端的消息: ')
          client_socket.send(message.encode('utf-8'))
          server_file.write(f'发送给客户端: {message}\n')
          if input("是否要继续？Y/N") == "N":
              break

  # 关闭连接
  client_socket.close()
  server_socket.close()


客户端代码：

  import socket

  # 创建 socket 对象
  client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  # 连接到服务器
  server_address = ('192.168.10.42', 8888)
  client_socket.connect(server_address)

  # 打开文件以记录消息
  with open('client_messages.txt', 'a', encoding='utf-8') as client_file:
      while True:
          # 发送消息给服务器
          message = input('请输入要发送给服务器的消息: ')
          client_socket.send(message.encode('utf-8'))
          client_file.write(f'发送给服务器: {message}\n')

          # 接收服务器消息
          data = client_socket.recv(1024).decode('utf-8')
          if not data:
              break
          print('服务器说: {}'.format(data))
          client_file.write(f'服务器回复: {data}\n')
          if input("是否继续Y/N？") == "N":
              break

  # 关闭连接
  client_socket.close()